#pragma once

#include <iostream>
#include <functional>
#include <string>
#include <cstdio>
#include <unistd.h>

using namespace std;

void serviceIO(int sock)
{
    char buffer[1024];
    while (true)
    {
        ssize_t n = read(sock, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            // 暂时把读到的数据当成字符串
            buffer[n] = 0;
            cout << "recv message: " << buffer << endl;

            // 构建服务端回应
            string outbuffer = buffer;
            outbuffer += "server[echo]";

            write(sock, outbuffer.c_str(), outbuffer.size());
        }
        // n为0时，代表客户端退出了，即文件的写入端关闭了。
        else if (n == 0)
        {
            cout << "Client quit, me too!" << endl;
            break;
        }
    }
    close(sock);
}
class Task
{
    using func_t = std::function<void(int)>;

public:
    Task()
    {
    }

    Task(int sock, func_t func)
        : _sock(sock), _callback(func)
    {
    }

    void operator()()
    {
        _callback(_sock);
    }

private:
    int _sock;
    func_t _callback;
};
